package com.test.springboot3.springboot3testdemo1.config;

import java.util.concurrent.Executor;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * Created with IntelliJ IDEA.
 *
 * @author： liuziyang
 * @date： 2024/8/24-10:18
 * @description：
 * @modifiedBy：
 * @version: 1.0
 */
@Configuration
public class AsyncConfiguration implements AsyncConfigurer {
  @Override
  public Executor getAsyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    // 设置核心线程数
    executor.setCorePoolSize(3);
    // 设置最大线程数
    executor.setMaxPoolSize(5);
    // 设置队列大小
    executor.setQueueCapacity(Integer.MAX_VALUE);
    // 设置线程活跃时间(秒)
    executor.setKeepAliveSeconds(30);
    // 设置线程名前缀+分组名称
    executor.setThreadNamePrefix("asyncThread-");
    executor.setThreadGroupName("asyncThreadGroup");
    // 所有任务结束后关闭线程池
    executor.setWaitForTasksToCompleteOnShutdown(true);
    // 初始化
    executor.initialize();
    return executor;
  }

  @Override
  public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
    return (throwable, method, obj) -> {
      System.out.println("异步调用，异常捕获---------------------------------");
      System.out.println("Exception message - " + throwable.getMessage());
      System.out.println("Method name - " + method.getName());
      for (Object param : obj) {
        System.out.println("Parameter value - " + param);
      }
      System.out.println("异步调用，异常捕获---------------------------------");
    };
  }
}
